package com.alageek.personalblog.service.impl;

import com.alageek.personalblog.dao.UserMapper;
import com.alageek.personalblog.entity.doo.User;
import com.alageek.personalblog.entity.doo.UserExample;
import com.alageek.personalblog.entity.vo.UserVo;
import com.alageek.personalblog.service.RoleService;
import com.alageek.personalblog.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 通用逻辑：用户服务
 * @author AlaGeek
 */
@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final RoleService roleService;

    public UserServiceImpl(UserMapper userMapper, RoleService roleService) {
        this.userMapper = userMapper;
        this.roleService = roleService;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andAccountEqualTo(s);
        List<User> userList = userMapper.selectByExample(example);
        if (userList == null || userList.size() == 0) {
            throw new UsernameNotFoundException("账户不存在");
        }
        UserVo userVo = new UserVo(userList.get(0));
        userVo.setRoles(roleService.findByUserId(userVo.getId()));
        return userVo;
    }

    @Override
    public int saveSelective(User user) {
        return userMapper.insertSelective(user);
    }

    @Override
    public int removeById(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int modifyByIdSelective(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public User findById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<User> findByParam(User user) {
        UserExample example = new UserExample();
        return userMapper.selectByExample(example);
    }

}
